package com.starcrown;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

/**
 * @author ACong
 * @since 2025/8/11 8:56
 */
public class ImageCompressor {
    public static void main(String[] args) {
        try {
            // 输入和输出文件路径  // 替换为你的图像路径
            File inputFile = new File("C:\\Users\\1\\Desktop\\压缩\\e.jpg");
            File outputFile = new File("C:\\Users\\1\\Desktop\\压缩\\b.jpg");

            // 压缩图像 // JPEG 压缩质量（0.0f - 1.0f）
            compressImage(inputFile, outputFile, 0.7f);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void compressImage(File inputFile, File outputFile, float quality) throws IOException {
        // 读取输入图像
        BufferedImage image = ImageIO.read(inputFile);
        if (image == null) {
            throw new IOException("无法读取图像: " + inputFile.getName());
        }

        // 获取图像类型
        String formatName = inputFile.getName().toLowerCase().endsWith(".png") ? "png" : "jpeg";

        // 创建图像写入器
        ImageWriter writer = ImageIO.getImageWritersByFormatName(formatName).next();
        ImageOutputStream outputStream = ImageIO.createImageOutputStream(outputFile);
        writer.setOutput(outputStream);

        // 设置压缩参数
        ImageWriteParam writeParam = writer.getDefaultWriteParam();
        if (formatName.equals("jpeg")) {
            // JPEG 压缩
            writeParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
            // 设置压缩质量（0.0f - 1.0f）
            writeParam.setCompressionQuality(quality);
        } else if (formatName.equals("png")) {
            // PNG 压缩（移除元数据并优化）
            writeParam.setCompressionMode(ImageWriteParam.MODE_DEFAULT);
        }

        // 写入压缩后的图像
        writer.write(null, new IIOImage(image, null, null), writeParam);

        // 清理资源
        outputStream.flush();
        writer.dispose();
        outputStream.close();
    }
}